package com.wyx.springbootkafkaconsumerone.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

/**
 * @author wyx
 */
@Configuration
public class KafkaProducerConfiguration {

  private final static String KAFKA_BOOTSTRAP_SERVERS = "localhost:9092";

  @Bean
  public KafkaTemplate<String, String> kafkaTemplate() {
    return new KafkaTemplate(producerFactory());
  }

  @Bean
  public ProducerFactory<String, String> producerFactory() {
    return new DefaultKafkaProducerFactory<>(bsjProducerConfigs());
  }

  @Bean
  public Map<String, Object> bsjProducerConfigs() {
    Map<String, Object> props = new ConcurrentHashMap<>();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_BOOTSTRAP_SERVERS);
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

    props.put(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG, 1000);
    props.put(ProducerConfig.RECONNECT_BACKOFF_MAX_MS_CONFIG, 5000);
    props.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 1000);

    return props;
  }

}
